package com.kiell.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kiell.common.utils.PageUtils;
import com.kiell.common.utils.Query;
import com.kiell.common.utils.R;
import com.kiell.gulimall.ware.dao.PurchaseDetailDao;
import com.kiell.gulimall.ware.entity.PurchaseDetailEntity;
import com.kiell.gulimall.ware.entity.PurchaseEntity;
import com.kiell.gulimall.ware.feign.ProductFeignService;
import com.kiell.gulimall.ware.service.PurchaseDetailService;
import com.kiell.gulimall.ware.service.PurchaseService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service("purchaseDetailService")
public class PurchaseDetailServiceImpl extends ServiceImpl<PurchaseDetailDao, PurchaseDetailEntity> implements PurchaseDetailService {

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private PurchaseService purchaseService;
    
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         *    wareId: 123,//仓库id
         *    status: 123//状态
         */
        QueryWrapper<PurchaseDetailEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and((w)->{
                w.eq("purchase_id",key).or().eq("sku_id",key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            queryWrapper.eq("status",status);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)){
            queryWrapper.eq("ware_id",wareId);
        }
        IPage<PurchaseDetailEntity> page = this.page(
                new Query<PurchaseDetailEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * @param id
     * @return
     */
    @Override
    public List<PurchaseDetailEntity> listDetaileByPurchaseId(Long id) {
        List<PurchaseDetailEntity> list = this.list(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", id));
        return list;
    }

    /**
     * @param purchaseDetail
     */
    @Override
    public void saveDetail(PurchaseDetailEntity purchaseDetail) {
        Integer skuNum = purchaseDetail.getSkuNum();
        Long skuId = purchaseDetail.getSkuId();
        try {
            R info = productFeignService.info(skuId);
            Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");

            if(info.getCode() == 0){
                Double priceStr = (Double) data.get("price");
                if (!priceStr.isNaN()){
                    BigDecimal price = new BigDecimal(priceStr);
                    BigDecimal countPrice = price.multiply(BigDecimal.valueOf(skuNum));
                    purchaseDetail.setSkuPrice(countPrice);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        this.save(purchaseDetail);
    }

    /**
     * @param purchaseDetail
     */
    @Override
    public void updateDetailById(PurchaseDetailEntity purchaseDetail) {

        PurchaseDetailEntity entity = this.getById(purchaseDetail.getId());
        Integer skuNum = purchaseDetail.getSkuNum();
        Long skuId = purchaseDetail.getSkuId();
        if (entity.getSkuId() != skuId || entity.getSkuNum() != skuNum){
            try {
                R info = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");

                if(info.getCode() == 0){
                    Double priceStr = (Double) data.get("price");
                    if (!priceStr.isNaN()){
                        BigDecimal price = new BigDecimal(priceStr);
                        BigDecimal countPrice = price.multiply(BigDecimal.valueOf(skuNum));
                        purchaseDetail.setSkuPrice(countPrice);
                    }

                    Long purchaseId = purchaseDetail.getPurchaseId();
                    if (purchaseId != null){
                        PurchaseDetailEntity beforeDetail = this.getById(purchaseDetail.getId());
                        PurchaseEntity purchaseEntity = purchaseService.getById(purchaseId);
                        BigDecimal amount = purchaseEntity.getAmount();
                        amount = amount.subtract(beforeDetail.getSkuPrice()).add(purchaseDetail.getSkuPrice());
                        purchaseEntity.setAmount(amount);
                        purchaseEntity.setUpdateTime(new Date());
                        purchaseService.updateById(purchaseEntity);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }

        this.updateById(purchaseDetail);
    }

    /**
     * @param list
     */
    @Override
    public void removeDetialByIds(List<Long> list) {
        list.forEach(id->{
            PurchaseDetailEntity de = this.getById(id);
            Long purchaseId = de.getPurchaseId();
            if (purchaseId != null){
                PurchaseEntity purchaseEntity = purchaseService.getById(purchaseId);
                purchaseEntity.setUpdateTime(new Date());
                purchaseEntity.setAmount(purchaseEntity.getAmount().subtract(de.getSkuPrice()));
                purchaseService.updateById(purchaseEntity);
            }
        });
        this.removeByIds(list);
    }


}